package co.za.itweb.brainstormlite;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class LoginHandler extends DefaultHandler{

	LoginFeed _feed;
	LoginItem _item;
	String _lastElementName = "";
	final int RSS_NAME = 1;
	final int RSS_ID = 2;
	final int RSS_LOGIN = 3;
	final int RSS_EXPIRY = 4;
	StringBuilder buf;
	int depth = 0;
	int currentstate = 0;
	
	LoginHandler()
	{
	 buf =	new StringBuilder();
	}
	
	
	LoginFeed getFeed()
	{
		return _feed;
	}
	
	
	public void startDocument() throws SAXException
	{
		_feed = new LoginFeed();
		_item = new LoginItem();
	}
	public void endDocument() throws SAXException
	{
	}
	public void startElement(String namespaceURI, String localName,String qName, Attributes atts) throws SAXException
	{
		 buf =	new StringBuilder();
		depth++;
		if (localName.equals("auth"))
		{
			currentstate = 0;
			return;
		}
		
		if (localName.equals("user"))
		{
			_item = new LoginItem();
			return;
		}
		if (localName.equals("name"))
		{
			currentstate = RSS_NAME;
			return;
		}
		if (localName.equals("id"))
		{
			currentstate = RSS_ID;
			return;
		}
		if (localName.equals("login"))
		{
			currentstate = RSS_LOGIN;
			return;
		}
		if (localName.equals("expiry"))
		{
			currentstate = RSS_EXPIRY;
			return;
		}
		
		
		currentstate = 0;
	}
	
	public void endElement(String namespaceURI, String localName, String qName) throws SAXException
	{
		depth--;
		if (localName.equals("user"))
		{
			// add our item to the list!
			_feed.addItem(_item);
			return;
		}
		
		switch (currentstate)
		{
			case RSS_NAME:
				_item.set_name(buf.toString());
				currentstate = 0;
				break;
			case RSS_ID:
				_item.set_id(buf.toString());
				currentstate = 0;
				break;
			case RSS_LOGIN:
				_item.set_login(buf.toString());
				currentstate = 0;
				break;
			case RSS_EXPIRY:
				_item.set_expiry(buf.toString());
				currentstate = 0;
				break;
			
			default:
				return;
		}
	}
	 
	public void characters(char ch[], int start, int length)
	{
		if (buf!=null) {
	        for (int i=start; i<start+length; i++) {
	            buf.append(ch[i]);
	        }
	    }
		
	}
}
